<?php
namespace app\admin\controller;

use app\admin\model\ApiCompanyModel;
use app\admin\model\ApiProjectModel;
use app\admin\model\ApiSpotModel;
use app\admin\model\ApiSupplierModel;
use think\Db;

/**
 * Func 操作类
 *
 * Class ApiProjectController
 *
 * @package app\admin\controller
 */
class ApiProjectController extends BaseController
{
    /**
     * Func 列表
     */
    public function index()
    {
        $param = $this->request->param();

        // 时间
        if ($this->start_time && $this->end_time)
        {
            $condition['a.create_time'] = ['between', [
                strtotime($this->start_time), strtotime($this->end_time),
            ]];
        }

        // 关键词
        if ($this->keyword)
        {
            if ($this->searchType)
            {
                $condition[$this->searchType] = ['like', '%' . $this->keyword . '%'];
            } else {
                $condition['a.project_title|b.user_login|c.company_title|d.spot_title'] = ['like', '%' . $this->keyword . '%'];
            }
        }

        // 游玩日期
        if ($this->play_date)
        {
            $condition['a.project_date'] = ['eq', $this->play_date];
        }

        // 状态
        if ($this->status)
        {
            $condition['a.status'] = ['eq', $this->status];
        }

        $companyIdArr = (new ApiCompanyModel())->getCompanyIdArr();

        $condition['a.id']          = ['gt', 0];
        $condition['a.company_id']  = ['in', $companyIdArr];

        // 字段
        $fieldArr = [
            'a.*', 'b.user_login', 'c.company_title', 'd.spot_title','(select count(*) from t_api_resume e where a.project_date = e.resume_date and a.spot_id = e.spot_id and e.status = 3 and a.project_join_num < a.project_total_num) as project_wait_num'
        ];

        // 连接表
        $joinArr = [
            ['user b', 'a.user_id = b.id', 'left'],
            ['api_company c', 'a.company_id = c.id', 'left'],
            ['api_spot d', 'a.spot_id = d.id', 'left'],
        ];

        $probj = new ApiProjectModel();

        // 数据
        $infos['list'] = $probj->getApiProjectListInfo(
            $condition, ['a.id' => 'desc'], ['page' => $this->page, 'limit' => $this->limit],
            $fieldArr, $joinArr
        );

        // 待审核
        $infos['waitCount'] = $probj->getApiProjectCount(array_merge($condition, ['a.status' => ['eq', 3]]),$joinArr);

        $infos['projectStatusArr'] = self::$projectStatusArr;

        $this->assign('infos', $infos);

        return $this->fetch();
    }

    /**
     * Func 添加
     */
    public function add()
    {
        $spobj = new ApiSpotModel();
        $coobj = new ApiCompanyModel();

        if ($this->request->isPost())
        {
            $param = $this->request->param();

            $result = $this->validate($param, 'ApiProject.add');
            if (!is_bool($result))
            {
                $this->error($result);
            }

            // 景区
            $getApispotOneInfo = $spobj->getApispotOneInfo(
                ['a.id' => ['eq', $param['spot_id'], 'a.status' => ['eq', 1]]],
                ['a.id' => 'desc'], ['a.id']
            );
            if (empty($getApispotOneInfo))
            {
                $this->error('景区不存在或已关闭');
            }

            // 旅行社
            $getApiCompanyOneInfo = $coobj->getApiCompanyOneInfo(
                ['a.id' => ['eq', $param['company_id'], 'a.status' => ['eq', 1]]],
                ['a.id' => 'desc'], ['a.id', 'a.user_id']
            );
            if (!$getApiCompanyOneInfo)
            {
                $this->error('旅行社不存在或已关闭');
            }
            if (!in_array($getApiCompanyOneInfo['id'], $coobj->getCompanyIdArr()))
            {
                $this->error('您无权操作');
            }

            // 添加和更新的字段信息
            $data1 = self::getPostParamInfo([
                'project_title', 'project_total_num', 'project_date', 'project_desc',
                'address', 'admin_id', 'admin_name', 'admin_time', 'admin_desc'
            ]);

            // 附加参数
            $data2['spot_id']   = $getApispotOneInfo['id'];         // 景区id
            $data2['user_id']   = $getApiCompanyOneInfo['user_id']; // 用户id
            $data2['company_id']= $getApiCompanyOneInfo['id'];      // 旅行社id
            $data2['status'] = session('admin_is_operate') == 1 ? 1 : 3; // 非平台添加需要审核

            // 添加的数据
            $data = array_merge((array)$data1, (array)$data2);

            // 实例化模型类
            $probj = new ApiProjectModel();

            // 查询数据是否存在
            $condition_CH['a.company_id']       =   ['eq', $getApiCompanyOneInfo['id']];
            $condition_CH['a.project_title']    =   ['eq', trim($data['project_title'])];
            $condition_CH['a.project_date']     =   ['eq', trim($data['project_date'])];
            $getApiProjectCount = $probj->getApiProjectCount($condition_CH);
            if (!empty($getApiProjectCount))
            {
                $this->error('【' . $data['project_date'] . '】' . trim($data['project_title']) . '已存在');
            }

            if ($id = $probj->addOrUpdateApiProjectInfo($data))
            {
                $probj->triggerProjectUpdateData($id);

                $this->success('添加成功!', url('index', []));

            } else {
                $this->error('添加失败,请稍后重试');
            }
        }

        // 景区
        $detail['getApispotListInfo'] = $spobj->getApispotListInfo(
            ['a.status' => ['eq', 1]], ['a.id' => 'desc'], ['page' => 1, 'limit' => 100], ['a.id', 'a.spot_title']
        );

        // 企业
        $conditionCO['a.id']     = ['in', $coobj->getCompanyIdArr()];
        $conditionCO['a.status'] = ['eq', 1];
        $detail['getApiCompanyListInfo'] = $coobj->getApiCompanyListInfo(
            $conditionCO, ['a.id' => 'desc'], ['page' => 1, 'limit' => 100], ['a.id', 'a.company_title']
        );

        $this->assign('detail', $detail);

        return $this->fetch();
    }

    /**
     * Func 修改
     */
    public function edit()
    {
        $param = $this->request->param();

        $spobj = new ApispotModel();
        $probj = new ApiProjectModel();
        $coobj = new ApiCompanyModel();

        $detail = $probj->getApiProjectOneInfo(['uuid' => $param['uuid']], ['id' => 'desc']);
        if (!$detail)
        {
            $this->error('信息不存在');
        }

        if ($this->request->isPost())
        {
            $result = $this->validate($param, 'ApiProject.edit');
            if (!is_bool($result))
            {
                $this->error($result);
            }

            // 景区
            $getApispotOneInfo = $spobj->getApispotOneInfo(
                ['a.id' => ['eq', $param['spot_id'], 'a.status' => ['eq', 1]]],
                ['a.id' => 'desc'], ['a.id']
            );
            if (!$getApispotOneInfo)
            {
                $this->error('景区不存在或已关闭');
            }

            // 旅行社
            $getApiCompanyOneInfo = (new ApiCompanyModel())->getApiCompanyOneInfo(
                ['a.id' => ['eq', $param['company_id'], 'a.status' => ['eq', 1]]],
                ['a.id' => 'desc'], ['a.id','a.user_id']
            );
            if(!$getApiCompanyOneInfo)
            {
                $this->error('旅行社不存在或已关闭');
            }
            if (!in_array($getApiCompanyOneInfo['id'], $coobj->getCompanyIdArr()))
            {
                $this->error('您无权操作');
            }

            // 查询数据是否存在
            $conditionRE['a.company_id']   = array('eq', $getApiCompanyOneInfo['id']);
            $conditionRE['a.project_title']   = array('eq', trim($param['project_title']));
            $conditionRE['a.project_date'] = array('eq', trim($param['project_date']));
            $getApiProjectOneInfo1 = $probj->getApiProjectOneInfo($conditionRE,['a.id'=>'desc'],['id']);
            if ($getApiProjectOneInfo1 && $getApiProjectOneInfo1['id'] != $detail['id'])
            {
                $this->error('【' . $param['project_date'] . '】' . trim($param['project_title']) . '已存在');
            }

            // 添加和更新的字段信息
            $data1 = self::getPostParamInfo([
                'project_title', 'project_total_num', 'project_date', 'project_desc',
                'address', 'admin_id', 'admin_name', 'admin_time', 'admin_desc'
            ]);

            // 附加参数
            $data2['spot_id']   = $getApispotOneInfo['id'];    // 景区id
            $data2['user_id']   = $getApiCompanyOneInfo['user_id']; // 用户id
            $data2['company_id']= $getApiCompanyOneInfo['id']; // 旅行社id

            if (session('admin_is_operate') == 1)
            {
                $data2['status'] = $param['status'];
            } else {
                if($detail['status'] != 3)
                {
                    $this->error('只有待审核状态，才能修改');
                }
            }

            // 修改的数据
            $data = array_merge((array)$data1, (array)$data2);

            if ($probj->addOrUpdateApiProjectInfo($data, $detail['id']))
            {
                $probj->triggerProjectUpdateData($detail['id']);

                $this->success('修改成功!', url('index', []));

            } else {
                $this->error('修改失败,请稍后重试');
            }
        }

        // 景区
        $detail['getApispotListInfo'] = $spobj->getApispotListInfo(
            ['a.status' => ['eq', 1]], ['a.id' => 'desc'], ['page' => 1, 'limit' => 100], ['a.id', 'a.spot_title']
        );

        // 企业
        $conditionCO['a.id']     = ['in', $coobj->getCompanyIdArr()];
        $conditionCO['a.status'] = ['eq', 1];
        $detail['getApiCompanyListInfo'] = $coobj->getApiCompanyListInfo(
            $conditionCO, ['a.id' => 'desc'], ['page' => 1, 'limit' => 100], ['a.id', 'a.company_title']
        );

        $detail['projectStatusArr'] = self::$projectStatusArr;

        $this->assign('detail', $detail);

        return $this->fetch();
    }

    /**
     * Func 供应商列表
     */
    public function indexa()
    {
        $param = $this->request->param();

        $getApiProjectOneInfo = (new ApiProjectModel())->getApiProjectOneInfo(
            ['a.uuid' => $param['uuid']], ['a.id' => 'desc'],['id','spot_id','project_date','project_total_num','project_join_num']
        );
        if (!$getApiProjectOneInfo)
        {
            $this->error('参数错误');
        }

        // 时间
        if ($this->start_time && $this->end_time)
        {
            $condition['a.create_time'] = ['between', [
                strtotime($this->start_time), strtotime($this->end_time),
            ]];
        }

        // 关键词
        if ($this->keyword)
        {
            if ($this->searchType)
            {
                $condition[$this->searchType] = ['like', '%' . $this->keyword . '%'];
            } else {
                $condition['a.resume_name'] = ['like', '%' . $this->keyword . '%'];
            }
        }

        $status = 3; // 待审核
        // 如果人数已满，新添加的游客不在显示到列表中
        if($getApiProjectOneInfo['project_join_num'] >= $getApiProjectOneInfo['project_total_num'])
        {
            $status= -10000; // 不存在的数据
        }


        $condition['a.spot_id']     = ['eq', $getApiProjectOneInfo['spot_id']];
        $condition['a.resume_date'] = ['eq', $getApiProjectOneInfo['project_date']];

        // 连接
        $joinArr = [
            ['api_supplier b', 'a.supplier_id = b.id', 'left'],
        ];

        $infos['list'] =  Db::name ('api_resume')
            ->alias ( 'a' )
            ->field(['a.*','b.supplier_title'])
            ->join ( $joinArr )
            ->where($condition)
            ->where("a.`project_id`={$getApiProjectOneInfo['id']} or a.`status` = $status")
            ->order(['a.status'=>'desc'])
            ->paginate ( 10 , false , [ 'page' =>$this->page ] );

        $infos['resumeStatusArr'] = self::$resumeStatusArr;

        $this->assign('param', $param);
        $this->assign('infos', $infos);

        return $this->fetch();
    }

    /**
     * Func 绑定
     */
    public function binds()
    {
        $data = $this->request->param();

        if(empty($data['ids']))
        {
            $this->error('请选择要绑定的游客');
        }

        if (session('admin_is_operate') != 1)
        {
            $this->error('您无权操作');
        }

        $probj = new ApiProjectModel();

        $getApiProjectOneInfo = $probj->getApiProjectOneInfo(
            ['a.uuid' => $data['uuid']], ['a.id' => 'desc'],
            ['id', 'spot_id', 'project_date', 'project_total_num', 'project_join_num','status']
        );
        if (!$getApiProjectOneInfo)
        {
            $this->error('参数错误');
        }
        if($getApiProjectOneInfo['status'] != 1)
        {
            $this->error('需求不是已通过状态，不能操作');
        }

        // 如果已加入数+提交数 > 需求人数需要提示错误
        if((count($data['ids'])+$getApiProjectOneInfo['project_join_num']) > $getApiProjectOneInfo['project_total_num'])
        {
            $this->error('超过需求总人数');
        }

        $condition['id']            =   ['in', $data['ids']];
        $condition['spot_id']       =   ['eq', $getApiProjectOneInfo['spot_id']];
        $condition['resume_date']   =   ['eq', $getApiProjectOneInfo['project_date']];
        $condition['project_id']    =   ['eq', 0];
        $condition['status']        =   ['eq', 3];
        Db::name ('api_resume')->where($condition)->update([
            'status' => 1,
            'handle_time' => time(),
            'project_id'=>$getApiProjectOneInfo['id'],
        ]);

        // 更新数据
        $probj->triggerProjectUpdateData($getApiProjectOneInfo['id']);

        $this->success("更新成功！");
    }

    /**
     * func 可用项目
     * @return void
     */
    public function groups()
    {
        $params = $this->request->param();
        $data = [];
        if($params['spot_uuid'] && trim($params['resume_date']))
        {
           $getApiSpotOneInfo = (new ApiSpotModel())->getApiSpotOneInfo(
               ['a.uuid' => $params['spot_uuid']],['a.id'=>'desc'],['a.id']
           );
           if($getApiSpotOneInfo)
           {
               $lastProjectListInfo = (new ApiProjectModel())->lastProjectListInfo(
                   ['spot_id' => $getApiSpotOneInfo['id'], 'date' => $params['resume_date']]
               );
               foreach ($lastProjectListInfo as $val)
               {
                   $number = $val['project_total_num']-$val['project_join_num'];
                   $data[] = [
                       'uuid'=>$val['uuid'],
                       'name'=>$val['project_title'].'（剩余'.$number.'人）',
                       'number'=>$val['project_total_num']-$val['project_join_num'],
                   ];
               }
           }
        }
        $this->success('成功','',$data);
    }
}